package xiegd.com.springbootuse.demo.elaticsearch.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xiegd.com.springbootuse.demo.elaticsearch.entity.Student;

import java.util.Map;

/**
 * @Description:
 * @Author: xieguangda
 * @Date: 2021年08月09日 14:23
 */
@RestController
@RequestMapping(value = "/es")
public class ESController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @PostMapping("/addES")
    public void addES(Student user ) throws Exception{
      //  restHighLevelClient.asyncSearch();
        IndexRequest indexRequest = new IndexRequest("student");
       // User user = new User("hinzzz",18,"亚历山大大西北出来");
        if( user == null || (user.getAge() == null)){
            user = new Student("xieguangda",26,44243,93.3);
        }
        String jsonString = JSONObject.toJSONString(user);
        System.out.println("jsonSgring:::" + jsonString);
        //设置要保存的内容
       // indexRequest.source(jsonString, XContentType.JSON);
        //执行创建索引和保存数据
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println(index);

    }

    @GetMapping("/getData/{sid}")
    public Student getData(@PathVariable("sid") String sid)throws Exception{
        GetRequest getIndexRequest = new GetRequest("student",sid);
        GetResponse getResponse = restHighLevelClient.get(getIndexRequest,  RequestOptions.DEFAULT);
        System.out.println("getResponse = " + getResponse);
        String index = getResponse.getIndex();
        String id = getResponse.getId();
        Student s = null;
        if (getResponse.isExists()) {
            Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();//数据转map
            if(sourceAsMap != null){
                 s = JSON.parseObject(JSON.toJSONString(sourceAsMap), Student.class);
            }
        }

        return  s;
    }

    @PostMapping("/complexSearch")
   public  void complexSearch()throws Exception{
        //搜索address中包含北京的所有人的年龄分布以及平均年龄，平均薪资
        SearchRequest searchRequest = new SearchRequest();

        //返回所有结果
        //System.out.println("查询所有数据" + client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS));

        //指定索引
        //searchRequest.indices("user","my_index");
        //System.out.println("查询多个索引" + client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS));


        //查询地址
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("address","北京"));

        //查询年龄分布
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("allAge").field("age").size(100);
        searchSourceBuilder.aggregation(termsAggregationBuilder);

        //查询平均年龄
        AvgAggregationBuilder avgAggregationBuilder = AggregationBuilders.avg("ageAvg").field("age");
        searchSourceBuilder.aggregation(avgAggregationBuilder);

        //查询平均薪资
        AvgAggregationBuilder avgAggregationBuilder1 = AggregationBuilders.avg("salaryAvg").field("salary");
        searchSourceBuilder.aggregation(avgAggregationBuilder1);

        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("search = " + searchResponse);


        //将检索结果封装为Bean
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            String sourceAsString = searchHit.getSourceAsString();
            Student user = JSON.parseObject(sourceAsString, Student.class);
            System.out.println(user);

        }

        //获取聚合信息
        Aggregations aggregations = searchResponse.getAggregations();

        Terms ageAgg1 = aggregations.get("allAge");

        for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            System.out.println("年龄："+keyAsString+" ==> "+bucket.getDocCount());
        }
        Avg ageAvg1 = aggregations.get("ageAvg");
        System.out.println("平均年龄："+ageAvg1.getValue());

        Avg balanceAvg1 = aggregations.get("salaryAvg");
        System.out.println("平均薪资："+balanceAvg1.getValue());

    }

}
